package qnb._config.aop;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import qnb.entity.SysPower;
import qnb.service.SysPowerService;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangxin
 * @date 2019/6/1-17:41
 */
@Aspect
@Component
public class ControllerAop {
    @Autowired
    private SysPowerService sysPowerService;


    /**
     * 获取权限代码
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(public * qnb.controller..forward*(..))")
    public Object before(ProceedingJoinPoint pjp) throws Throwable {
        //获取参数
        Object[] args = pjp.getArgs();

        //判断最后一个参数类型
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Class[] paramTypeArray = methodSignature.getParameterTypes();
        if (paramTypeArray.length>0){
            if (ModelAndView.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
                //如果方法的参数列表最后一个参数是ModelAndView类型，则给其赋值
                ModelAndView modelAndView = (ModelAndView) args[args.length - 1];

                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                HttpSession session = request.getSession();
                //查询数据
                List<String> codes = sysPowerService.getCodes(session);

                modelAndView.addObject("code",codes);

                args[args.length - 1] =modelAndView;
            }
        }
        return pjp.proceed(args);
    }

}
